<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 门店管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\deerhome\Shop
     */
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Shop;

    }

    /**
     * 查看
     */
    public function index()
    {
        $keyValue=$this->request->request("keyValue");
        $mdname=$this->request->request("mdname");
        $this->searchFields = "mdname";
        if (!$this->request->isAjax()) {
            $multiple=$this->request->param('multiple','','trim');
            $this->assignconfig("multiple",$multiple);
            $this->assign("multiple", $multiple);
            $this->assignconfig('dialog', (int)$this->request->get('dialog'));
            return $this->view->fetch();
        }
        $where2=[];
        if(isset($keyValue)){
            $where2['shop.id']=$keyValue;
        }
        if(isset($mdname) && $mdname!=''){
            $where2['shop.mdname']=['LIKE',"%$mdname%"];
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->with("user")
            ->withCount("Worker",false)
            ->where($where2)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
        
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign("typeList", $this->model->getTypeList());
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['mdname']=trim($params['mdname']);
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $this->model->validateFailException()->validate(
                ['mdname' => ['unique'=>'deerhome_shop,mdname']],
			    ['mdname.unique'=> '名称已经存在，请更换']
            );
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign("typeList", $this->model->getTypeList());
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['mdname']=trim($params['mdname']);
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $row->validateFailException()->validate(
                ['mdname' => ['unique'=>'deerhome_shop,mdname,'.$row['id']]],
			    ['mdname.unique'=> '名称已经存在，请更换']
            );
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $has=Db::name("deerhome_worker")->where('jz_shop_id','in',$ids)->count();
        if($has>0){
            $this->error("该门店下有服务人员，不能删除");
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


}
